package Offer来了.JUC容器.同步包装方法;

import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CollectionsDemo {
    public static void main(String[] args) throws InterruptedException {
        //创建一个基础的有序集合
        SortedSet<String> elementSet = new TreeSet<>();
        //增加元素
        elementSet.add("element 1");
        elementSet.add("element 2");

        //将element包装成一个同步容器
        SortedSet<String> sortedSet = Collections.synchronizedSortedSet(elementSet);
        //输出容器中的元素
        System.out.println("SortedSet is :" + sortedSet);
        CountDownLatch latch = new CountDownLatch(5);
        ExecutorService pool = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            pool.submit(() -> {
                //向同步容器中增加一个元素
                sortedSet.add("element " + (3 + finalI));
                System.out.println("add element" + (3 + finalI));
                latch.countDown();
            });
        }
        latch.await();
        //输出容器中的元素
        System.out.println("SortedSet is :" + sortedSet);
    }
}
